<template>
  <div class="admin-layout">
    <!-- 侧边栏 -->
    <aside class="sidebar" :class="{ collapsed: isSidebarCollapsed }">
      <div class="sidebar-header">
        <div class="logo">
          <h2 v-if="!isSidebarCollapsed">系统管理中心<span>面板</span></h2>
          <h2 v-else>M</h2>
        </div>
        <!-- <el-button class="collapse-btn" link @click="toggleSidebar">
          <el-icon>
            <Expand v-if="isSidebarCollapsed" />
            <Fold v-else />
          </el-icon>
        </el-button> -->
      </div>

      <el-menu :default-active="activeMenu" class="sidebar-menu" :collapse="isSidebarCollapsed"
        background-color="#304156" text-color="#bfcbd9" active-text-color="#409eff" @select="handleMenuSelect">
        <el-menu-item index="dashboard">
          <el-icon>
            <Odometer />
          </el-icon>
          <template #title>仪表盘</template>
        </el-menu-item>
        <!-- 动态生成菜单 -->
        <template v-for="menu in menuData" :key="menu.menuId">
          <!-- 有子菜单的情况 -->
          <el-sub-menu v-if="menu.children && menu.children.length > 0" :index="menu.name">
            <template #title>
              <el-icon v-if="menu.icon">
                <component :is="menu.icon" />
              </el-icon>
              <span>{{ menu.menuName }}</span>
            </template>
            <!-- 递归渲染子菜单 -->
            <template v-for="child in menu.children" :key="child.menuId">
              <el-menu-item v-if="!child.children || child.children.length === 0" :index="child.name">
                <el-icon v-if="child.icon">
                  <component :is="child.icon" />
                </el-icon>
                <template #title>{{ child.menuName }}</template>
              </el-menu-item>
              <!-- 如果还有更深层的子菜单，可以继续递归 -->
              <el-sub-menu v-else :index="child.name">
                <template #title>
                  <el-icon v-if="child.icon">
                    <component :is="child.icon" />
                  </el-icon>
                  <span>{{ child.menuName }}</span>
                </template>
                <el-menu-item v-for="grandchild in child.children" :key="grandchild.menuId" :index="grandchild.name">
                  <el-icon v-if="grandchild.icon">
                    <component :is="grandchild.icon" />
                  </el-icon>
                  <template #title>{{ grandchild.menuName }}</template>
                </el-menu-item>
              </el-sub-menu>
            </template>
          </el-sub-menu>

          <!-- 无子菜单的情况 -->
          <el-menu-item v-else :index="menu.name">
            <el-icon v-if="menu.icon">
              <component :is="menu.icon" />
            </el-icon>
            <template #title>{{ menu.menuName }}</template>
          </el-menu-item>
        </template>
      </el-menu>
    </aside>

    <!-- 主内容区域 -->
    <div class="main-content">
      <!-- 顶部导航栏 -->
      <header class="topbar">
        <div class="topbar-left">
          <el-button class="menu-toggle" link @click="toggleSidebar">
            <el-icon>
              <Expand v-if="isSidebarCollapsed" />
              <Fold v-else />
            </el-icon>
          </el-button>

          <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>{{ currentPageTitle }}</el-breadcrumb-item>
          </el-breadcrumb>
        </div>

        <div class="topbar-right">
          <el-dropdown>
            <el-badge :value="3" class="notification-badge">
              <el-button link>
                <el-icon :size="20">
                  <Bell />
                </el-icon>
              </el-button>
            </el-badge>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item>您有一条新消息</el-dropdown-item>
                <el-dropdown-item>系统更新提醒</el-dropdown-item>
                <el-dropdown-item>订单状态变更</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>

          <el-dropdown>
            <div class="user-profile">
              <el-avatar :size="32" src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png" />
              <span class="username">{{userStore.getNickName || '管理员'}}</span>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="toUser">
                  <el-icon>
                    <User />
                  </el-icon>个人中心
                </el-dropdown-item>
                <el-dropdown-item @click="toStore">
                  <el-icon>
                    <Setting />
                  </el-icon>商城首页
                </el-dropdown-item>
                <el-dropdown-item divided @click="logout">
                  <el-icon>
                    <SwitchButton />
                  </el-icon>退出登录
                </el-dropdown-item>
                <el-dropdown-item divided @click="toTest">
                  <el-icon>
                    <SwitchButton />
                  </el-icon>测试
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </header>

      <!-- 路由内容区域 -->
      <div class="content-wrapper">
        <RouterView />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute, RouterView } from 'vue-router'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import {logout as logoutFromAPI} from '@/api/common/login'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()
const isSidebarCollapsed = ref(false)
const activeMenu = ref('dashboard')
const menuData = ref([])

// 注册所有图标为全局组件
import { getCurrentInstance } from 'vue'
const instance = getCurrentInstance()
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  instance.appContext.app.component(key, component)
}

// 动态生成标题映射
const currentPageTitle = computed(() => {
  // 默认标题
  const defaultTitles = {
    'dashboard': '仪表盘',
  }

  // 从菜单数据中提取标题映射
  const menuTitles = {}
  const extractTitles = (menus) => {
    menus.forEach(menu => {
      menuTitles[menu.name] = menu.menuName
      if (menu.children && menu.children.length > 0) {
        extractTitles(menu.children)
      }
    })
  }

  extractTitles(menuData.value)

  // 合并默认标题和菜单标题
  const titleMap = { ...defaultTitles, ...menuTitles }
  return titleMap[route.name] || '仪表盘'
})

const toggleSidebar = () => {
  isSidebarCollapsed.value = !isSidebarCollapsed.value
}

// 动态生成路由映射
const handleMenuSelect = (index) => {
  activeMenu.value = index

  // 构建路由映射
  const routeMap = {
    'dashboard': '/management/dashboard',
  }

  const buildRouteMap = (menus, parentPath = '/management') => {
    menus.forEach(menu => {
      const fullPath = parentPath + '/' + menu.path
      routeMap[menu.name] = fullPath

      if (menu.children && menu.children.length > 0) {
        buildRouteMap(menu.children, fullPath)
      }
    })
  }

  buildRouteMap(menuData.value)

  if (routeMap[index]) {
    router.push(routeMap[index])
  }
}

const getMenuListInit = () => {
  // let uid = userStore.getUserId
  // let res = getMenuList(uid)
  // res.then(res => {
  //   const sortedMenuData = res.data.sort((a, b) => a.orderNum - b.orderNum)

  //   const sortChildren = (menus) => {
  //     menus.forEach(menu => {
  //       if (menu.children && menu.children.length > 0) {
  //         menu.children.sort((a, b) => a.orderNum - b.orderNum)
  //         sortChildren(menu.children)
  //       }
  //     })
  //   }
    
  //   sortChildren(sortedMenuData)
    
    menuData.value = userStore.getMenus
    // addManagementRoutes(sortedMenuData)
    // userStore.setMenuData=sortedMenuData
  // })
}

const logout = () => {
  // 执行退出登录逻辑
  // let auth="Bearer "+userStore.getToken
  let res = logoutFromAPI(userStore.getToken)
  
  userStore.clearUserData()
  router.push('/login')
  //console.log(router.getRoutes())

}

const toStore = () => {
  router.push('/store')
  // console.log(router.getRoutes())
}

const toUser = () => {
  router.push('/me')
}

const toTest = () => {
  // console.log(userStore.getRoles)
  
}

onMounted(() => {
  getMenuListInit()
})
</script>

<style scoped>
.admin-layout {
  display: flex;
  min-height: 100vh;
  background-color: #f0f2f5;
}

/* 侧边栏样式 */
.sidebar {
  width: 210px;
  background-color: #304156;
  color: #fff;
  transition: width 0.3s ease;
  display: flex;
  flex-direction: column;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 1000;
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.1);
}

.sidebar.collapsed {
  width: 64px;
}

.sidebar-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  height: 60px;
  border-bottom: 1px solid #43546a;
}

.logo h2 {
  margin: 0;
  color: #fff;
  font-size: 20px;
  white-space: nowrap;
  overflow: hidden;
}

.logo h2 span {
  color: #409eff;
}

.collapse-btn {
  color: #bfcbd9;
  font-size: 20px;
  transition: transform 0.3s;
}

.collapse-btn:hover {
  color: #fff;
  transform: scale(1.1);
}

.sidebar-menu {
  border: none;
  flex: 1;
  overflow-y: auto;
}

.sidebar-menu:not(.el-menu--collapse) {
  width: 210px;
}

/* 主内容区域 */
.main-content {
  flex: 1;
  margin-left: 210px;
  transition: margin-left 0.3s ease;
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}

.sidebar.collapsed+.main-content {
  margin-left: 64px;
}

/* 顶部导航栏 */
.topbar {
  height: 60px;
  background: #fff;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  z-index: 999;
  position: sticky;
  top: 0;
}

.topbar-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.menu-toggle {
  font-size: 20px;
  color: #606266;
}

.menu-toggle:hover {
  color: #409eff;
}

.topbar-right {
  display: flex;
  align-items: center;
  gap: 20px;
}

.notification-badge {
  display: flex;
  align-items: center;
}

.user-profile {
  display: flex;
  align-items: center;
  gap: 10px;
  cursor: pointer;
  padding: 5px 10px;
  border-radius: 20px;
  transition: background-color 0.3s;
}

.user-profile:hover {
  background-color: #f0f2f5;
}

.username {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
  white-space: nowrap;
}

/* 内容区域 */
.content-wrapper {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background-color: #f0f2f5;
}

/* 响应式设计 */
@media (max-width: 992px) {
  .sidebar {
    width: 64px;
  }

  .sidebar:not(.collapsed) .logo h2,
  .sidebar:not(.collapsed) .el-menu-item span,
  .sidebar:not(.collapsed) .el-sub-menu__title span {
    display: none;
  }

  .sidebar:not(.collapsed) .el-sub-menu__icon-arrow {
    display: none;
  }

  .main-content {
    margin-left: 64px;
  }
}

@media (max-width: 768px) {
  .sidebar {
    transform: translateX(-100%);
    transition: transform 0.3s ease;
  }

  .sidebar.collapsed {
    transform: translateX(0);
  }

  .main-content {
    margin-left: 0;
  }

  .topbar {
    padding: 0 15px;
  }

  .content-wrapper {
    padding: 15px;
  }
}

@media (max-width: 480px) {
  .topbar-right {
    gap: 10px;
  }

  .notification-badge .el-button {
    padding: 8px;
  }

  .user-profile .username {
    display: none;
  }

  .topbar-left {
    gap: 10px;
  }
}
</style>